import 'package:state_beacon/state_beacon.dart';
import '../models/encyclopedia_model.dart';

/// 百科状态管理
class EncyclopediaState {
  // 静态状态变量
  static List<EncyclopediaModel> _encyclopediaList = [];
  static Map<String, List<String>> _userFavoritesMap = {};
  static String _currentCategory = 'animal';

  // State Beacon 实例
  static final encyclopediaListBeacon =
      Beacon.writable<List<EncyclopediaModel>>(_encyclopediaList);
  static final userFavoritesMapBeacon =
      Beacon.writable<Map<String, List<String>>>(_userFavoritesMap);
  static final currentCategoryBeacon = Beacon.writable<String>(
    _currentCategory,
  );

  /// 初始化默认数据
  static void _initializeDefaultData() {
    if (_encyclopediaList.isNotEmpty) return; // 避免重复初始化

    // 初始化默认用户收藏数据
    _userFavoritesMap = {
      'admin': [
        'animal_001', // Ring-tailed Lemur
        'animal_003', // Aye-aye
        'animal_005', // Chameleon
        'plant_001', // Baobab Tree
        'plant_004', // Vanilla Orchid
      ],
      'user_001': [
        // 动物收藏
        'animal_001', // Ring-tailed Lemur
        'animal_002', // Aye-Aye
        'animal_004', // Panther Chameleon
        'animal_006', // Painted Reed Frog
        'animal_007', // Madagascar Weaver
        // 植物收藏
        'plant_001', // Baobab Tree
        'plant_002', // Ravenala Madagascariensis
        'plant_003', // Dracaena cinnabari
        'plant_005', // Helen Aloe Vera
        'plant_006', // Cycas thouarsii
      ],
    };

    _encyclopediaList = [
      // 动物分类数据
      EncyclopediaModel(
        encyclopediaId: 'animal_001',
        name: 'Ring-Tailed Lemur',
        description:
            'The ring tailed lemur (scientific name: Lemur catta) is one of the most recognizable endemic species in Madagascar. Due to its iconic black and white circular tail and unique social habits, it has become a must visit animal for global tourists visiting Madagascar and an important representative for understanding the unique characteristics of local biological evolution.',
        imageUrl: 'assets/images/ring_tailed_lemur.jpg',
        tags: ['Lemur Catta', 'Endangered Species'],
        viewCount: 1250,
        favoriteCount: 89,
        category: 'animal',
      ),
      EncyclopediaModel(
        encyclopediaId: 'animal_002',
        name: 'Aye-Aye',
        description:
            'The finger monkey (scientific name: Daubentonia madagascariensis) is a primate endemic to Madagascar and one of the most unique and mysterious species in the world. Due to its peculiar appearance, nocturnal habits, and unique foraging skills, it was once misunderstood by locals as an "ominous sign", but now it has become an iconic species for biodiversity conservation in Madagascar, and can be called a "miracle in the history of evolution".',
        imageUrl: 'assets/images/aye_aye.jpg',
        tags: ['Aye Aye', 'Endangered Species', 'Odor Marking'],
        viewCount: 980,
        favoriteCount: 67,
        category: 'animal',
      ),
      EncyclopediaModel(
        encyclopediaId: 'animal_003',
        name: 'Crowned Lemur',
        description:
            'The crowned lemur (scientific name: Eulemur coronatus) is a unique primate species in northern Madagascar, named after the iconic "coronal hair" on its head. It is known for its agile arboreal jumping ability and distinct male female characteristics. It is one of the most ornamental animals when exploring the rainforests of northern Madagascar and an important "seed spreader" in the local ecosystem.',
        imageUrl: 'assets/images/crowned_lemur.jpg',
        tags: ['Skilled In Jumping', 'Coronal Hair'],
        viewCount: 2100,
        favoriteCount: 156,
        category: 'animal',
      ),
      EncyclopediaModel(
        encyclopediaId: 'animal_004',
        name: 'Panther Chameleon',
        description:
            'One of the most brightly colored species in the chameleon family, only found in northern and eastern Madagascar. Adult males can transform into various colors such as red, blue, green, orange, etc. (females are mostly light brown or green) based on their emotions and environmental temperature. They can grow up to 50 centimeters in length and are skilled at observing prey (mainly insects) by independently rotating their eyes. They are common in the forests around Nosy Be Island.',
        imageUrl: 'assets/images/panther_chameleon.jpg',
        tags: ['Body Length Can Reach 50 Centimeters'],
        viewCount: 1450,
        favoriteCount: 98,
        category: 'animal',
      ),
      EncyclopediaModel(
        encyclopediaId: 'animal_005',
        name: 'Radiated Tortoise',
        description:
            'Radiated Tortoise of Madagascar: The "beauty responsible" species in the family Turtles, with radiating yellow patterns on its carapace. It can live for over 100 years and mainly inhabits the Spiny Forest in the south. Due to illegal hunting and habitat destruction, it is currently listed as a "critically endangered species" and can only be seen in protected areas.',
        imageUrl: 'assets/images/radiated_tortoise.jpg',
        tags: ['Life Expectancy Of Over 100 Years', 'Critically Endangered'],
        viewCount: 3200,
        favoriteCount: 234,
        category: 'animal',
      ),
      EncyclopediaModel(
        encyclopediaId: 'animal_006',
        name: 'Painted Reed Frog',
        description:
            'Madagascar Painted Reed Frog: With a body size of only 2-3 centimeters, it has brightly colored skin (mostly red, blue, and green) and is skilled at jumping between reeds or aquatic plants. It is mainly distributed in swamps and rainforests in the east and has almost no natural enemies because its skin can secrete toxins.',
        imageUrl: 'assets/images/painted_reed_frog.jpg',
        tags: ['Brightly Colored', 'No Natural Enemies'],
        viewCount: 890,
        favoriteCount: 45,
        category: 'animal',
      ),
      EncyclopediaModel(
        encyclopediaId: 'animal_007',
        name: 'Madagascar Weaver',
        description:
            'Madagascar Weaver: A small songbird with bright yellow feathers in males, skilled at weaving "hanging nests" (shaped like gourds) with grass and vines. It often inhabits farmland or forest edges in groups, with a crisp call and is a common "ecological indicator" in the local area.',
        imageUrl: 'assets/images/madagascar_weaver.jpg',
        tags: ['Small And Compact In Size', 'Clear And Crisp Call'],
        viewCount: 1800,
        favoriteCount: 123,
        category: 'animal',
      ),

      // 植物分类数据
      EncyclopediaModel(
        encyclopediaId: 'plant_001',
        name: 'Baobab Tree',
        description:
            'Adansonia is a large deciduous tree in the Malvaceae family, belonging to the genus Adansonia. Due to its unique appearance and important ecological and economic value, it is known as the "tree of life".In many African cultures, the baobab tree is regarded as a sacred symbol, often associated with folklore and traditional customs. Its hollow trunk can also be used as a temporary shelter, storage space, or sacrificial place. Some countries or cities consider it a symbol and develop tourism.',
        imageUrl: 'assets/images/baobab_tree.jpg',
        tags: ['Massive Tree Trunk', 'Store moisture'],
        viewCount: 2800,
        favoriteCount: 189,
        category: 'plant',
      ),
      EncyclopediaModel(
        encyclopediaId: 'plant_002',
        name: 'Ravenala Madagascariensis',
        description:
            'Ravendala madagascariensis, also known as Ravendala madagascariensis, also known as Ravendala madagascariensis, hibiscus, banana, water tree, etc., belongs to the family Ranunculaceae in the order of ginger. It is a single genus plant under the genus Ravendala madagascariensis, native to Madagascar. Due to the cup-shaped shape of its leaf sheath, which can store a large amount of water, its sap can also be consumed, providing an emergency water source for desert travelers, hence the name Traveler\'s Banana.',
        imageUrl: 'assets/images/ravendala_madagascariensis.jpg',
        tags: ['Madagascar\'s National Tree', 'Fan-shaped Arrangement'],
        viewCount: 1650,
        favoriteCount: 112,
        category: 'plant',
      ),
      EncyclopediaModel(
        encyclopediaId: 'plant_003',
        name: 'Dracaena cinnabari',
        description:
            'The Madagascar dragon blood tree (although named "Madagascar", actually native to Socotra Island in northeastern Africa) is a unique plant of the Asparagaceae family, characterized by an "umbrella shaped crown" and "red resin" as its core symbols, possessing both ecological and economic value. Currently, its survival is threatened.',
        imageUrl: 'assets/images/dracaena_cinnabari.jpg',
        tags: ['The Trunk Is Thick And Sturdy', 'Endangered Species'],
        viewCount: 1200,
        favoriteCount: 78,
        category: 'plant',
      ),
      EncyclopediaModel(
        encyclopediaId: 'plant_004',
        name: 'Angraecum Sesquipedale',
        description:
            'Angraecum sesquipedale is an epiphytic orchid of the Orchidaceae family, known for its unique flower spacing and inseparable connection with Darwin.The Great Comet Orchid is an epiphytic orchid of the Orchidaceae family, belonging to the Wuyi Orchid genus. Due to its long flower spacing, classic association with Darwin\'s theory of evolution, and native properties of Madagascar, it has become a representative species in the Orchidaceae family that combines scientific and ornamental value.',
        imageUrl: 'assets/images/angraecum_sesquipedale.jpg',
        tags: ['Scientific Value', 'Appreciation Value'],
        viewCount: 2100,
        favoriteCount: 145,
        category: 'plant',
      ),
      EncyclopediaModel(
        encyclopediaId: 'plant_005',
        name: 'Helen Aloe Vera',
        description:
            'Belonging to the monocotyledonous plant class of the angiosperms in the plant kingdom, the genus Aloe in the order Asparagales, it is a perennial plant. First described by Paul Auguste Danggie in 1929, the epithet "helenae" was coined in honor of Helen Decari, whose husband Raymond Decari was the first to describe many succulent plants in Madagascar.',
        imageUrl: 'assets/images/helen_aloe_vera.jpg',
        tags: ['Endangered Aloe Vera Varieties'],
        viewCount: 950,
        favoriteCount: 56,
        category: 'plant',
      ),
      EncyclopediaModel(
        encyclopediaId: 'plant_006',
        name: 'Cycas thouarsii',
        description:
            'Guangguo Cycas (also known as Tuoshi Cycas) is an evergreen tree like plant in the Cycas genus of the Cycas family. It is characterized by thick, feather like compound leaves and dioecious reproduction. It is native to tropical regions and has both ornamental and medicinal value. Currently, its overall survival status is stable, but local threats need to be taken into account.',
        imageUrl: 'assets/images/cycas_thouarsii.jpg',
        tags: ['Medicinal Value ', 'Tropical Region'],
        viewCount: 1350,
        favoriteCount: 89,
        category: 'plant',
      ),
      EncyclopediaModel(
        encyclopediaId: 'plant_007',
        name: 'Euphorbia Parvicyathophora',
        description:
            'Xiaoxu Euphorbia is an annual herbaceous plant belonging to the Euphorbiaceae family and the Euphorbiaceae genus. It is a unique species in southern Madagascar and is currently in a critically endangered state due to its high dependence on specific rocky habitats and habitat destruction. It is a key target for the protection of rare plants in the local area.',
        imageUrl: 'assets/images/euphorbia_parvicyathophora.jpg',
        tags: ['Endangered Aloe Vera Varieties', 'Rare Plants'],
        viewCount: 1100,
        favoriteCount: 67,
        category: 'plant',
      ),
    ];

    // 更新 Beacon 状态
    encyclopediaListBeacon.value = List.from(_encyclopediaList);
    userFavoritesMapBeacon.value = Map.from(_userFavoritesMap);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultData();
  }

  /// 获取所有百科数据
  static List<EncyclopediaModel> getAllEncyclopedia() {
    _initializeDefaultData();
    return _encyclopediaList;
  }

  /// 根据分类获取百科数据
  static List<EncyclopediaModel> getEncyclopediaByCategory(String category) {
    _initializeDefaultData();
    return _encyclopediaList
        .where((item) => item.category == category)
        .toList();
  }

  /// 获取动物分类数据
  static List<EncyclopediaModel> getAnimalEncyclopedia() {
    return getEncyclopediaByCategory('animal');
  }

  /// 获取植物分类数据
  static List<EncyclopediaModel> getPlantEncyclopedia() {
    return getEncyclopediaByCategory('plant');
  }

  /// 根据ID获取百科详情
  static EncyclopediaModel? getEncyclopediaById(String id) {
    _initializeDefaultData();
    try {
      return _encyclopediaList.firstWhere((item) => item.encyclopediaId == id);
    } catch (e) {
      return null;
    }
  }

  /// 增加访问数
  static void incrementViewCount(String id) {
    _initializeDefaultData();
    final index = _encyclopediaList.indexWhere(
      (item) => item.encyclopediaId == id,
    );
    if (index != -1) {
      final item = _encyclopediaList[index];
      _encyclopediaList[index] = item.copyWith(viewCount: item.viewCount + 1);
      encyclopediaListBeacon.value = List.from(_encyclopediaList);
    }
  }

  /// 更新收藏数
  static void updateFavoriteCount(String id, int change) {
    final encyclopediaIndex = _encyclopediaList.indexWhere(
      (item) => item.encyclopediaId == id,
    );
    if (encyclopediaIndex != -1) {
      final item = _encyclopediaList[encyclopediaIndex];
      _encyclopediaList[encyclopediaIndex] = item.copyWith(
        favoriteCount: item.favoriteCount + change,
      );
      encyclopediaListBeacon.value = List.from(_encyclopediaList);
    }
  }

  /// 切换收藏状态（基于用户ID）
  static bool toggleFavorite(String userId, String encyclopediaId) {
    _initializeDefaultData();

    // 确保用户收藏列表存在
    if (!_userFavoritesMap.containsKey(userId)) {
      _userFavoritesMap[userId] = [];
    }

    final userFavorites = _userFavoritesMap[userId]!;
    final index = userFavorites.indexOf(encyclopediaId);

    if (index != -1) {
      // 已收藏，取消收藏
      userFavorites.removeAt(index);
      updateFavoriteCount(encyclopediaId, -1);
      userFavoritesMapBeacon.value = Map.from(_userFavoritesMap);
      return false;
    } else {
      // 未收藏，添加收藏
      userFavorites.add(encyclopediaId);
      updateFavoriteCount(encyclopediaId, 1);
      userFavoritesMapBeacon.value = Map.from(_userFavoritesMap);
      return true;
    }
  }

  /// 检查用户是否已收藏某个百科
  static bool isFavorite(String userId, String encyclopediaId) {
    _initializeDefaultData();
    final userFavorites = _userFavoritesMap[userId];
    return userFavorites?.contains(encyclopediaId) ?? false;
  }

  /// 获取用户收藏的百科列表
  static List<EncyclopediaModel> getUserFavoriteEncyclopedia(String userId) {
    _initializeDefaultData();
    final userFavorites = _userFavoritesMap[userId] ?? [];
    return _encyclopediaList
        .where((item) => userFavorites.contains(item.encyclopediaId))
        .toList();
  }

  /// 设置当前分类
  static void setCurrentCategory(String category) {
    _currentCategory = category;
    currentCategoryBeacon.value = category;
  }

  /// 获取当前分类
  static String getCurrentCategory() {
    return _currentCategory;
  }

  /// 搜索百科
  static List<EncyclopediaModel> searchEncyclopedia(String keyword) {
    _initializeDefaultData();
    if (keyword.isEmpty) return _encyclopediaList;

    return _encyclopediaList.where((item) {
      return item.name.toLowerCase().contains(keyword.toLowerCase()) ||
          item.description.toLowerCase().contains(keyword.toLowerCase()) ||
          item.tags.any(
            (tag) => tag.toLowerCase().contains(keyword.toLowerCase()),
          );
    }).toList();
  }

  // Getters for reactive state
  static ReadableBeacon<List<EncyclopediaModel>> get encyclopediaList =>
      encyclopediaListBeacon;
  static ReadableBeacon<Map<String, List<String>>> get userFavoritesMap =>
      userFavoritesMapBeacon;
  static ReadableBeacon<String> get currentCategory => currentCategoryBeacon;
}
